package com.example.redisdemo.netty.handler;

import com.alibaba.fastjson.JSONObject;
import com.example.redisdemo.webrtc.message.Message;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import javax.websocket.RemoteEndpoint;
import java.time.LocalDateTime;


/**
 * 自定义句柄消息处理
 *TextWebSocketFrame  用于为websockt处理文本的对象
 * @author hexinglin
 * @created 2022-05-26 14:00
 **/
public  class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    //用于记录和管理所有客户端的channel
    private static ChannelGroup clients =
            new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    /**
     * 这里只做一个最简单的, 只有一个房间, 后面有需要自己可以改
     */
    private static Channel offer;
    private static Channel answer;

    /**
     * 客户端创建的时候触发，当客户端连接上服务端之后，就可以获取该channel，然后放到channelGroup中进行统一管理
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //id表示唯一的值，LongText 是唯一的 shortText不是唯一的
        System.out.println("客户端连接，当前的channel的短ID是：" + ctx.channel().id().asShortText());
        clients.add(ctx.channel());
      //  clients.writeAndFlush( new TextWebSocketFrame(ctx.channel().id().asShortText()+"上线了:" + LocalDateTime.now() ));

    }

    /**
     * 客户端销毁的时候触发
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //当handlerRemoved 被触发时候，channelGroup会自动移除对应的channel
        clients.remove(ctx.channel());
       // clients.writeAndFlush( new TextWebSocketFrame(ctx.channel().id().asShortText()+"离线了:" + LocalDateTime.now() ));

        if (offer != null && ctx.channel().id().asShortText().equals(offer.id().asShortText())) {
            offer = null;
        }
        if (answer != null && ctx.channel().id().asShortText().equals(answer.id().asShortText())) {
            answer = null;
        }
        System.out.println("客户端断开，当前被移除的channel的短ID是：" + ctx.channel().id().asShortText());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        //客户端传递过来的消息
        String content = msg.text();
        System.out.println("接收到了"+ctx.channel().id().asShortText()+"客户端的消息是:" + content);
        Message data = JSONObject.parseObject(content, Message.class);
        Message response = new Message();
        response.setOperation(data.getOperation());
        Channel session = ctx.channel();
        switch (data.getOperation()) {
            //加入房间
            case "into": {
                if (offer == null) {
                    offer = session;
                    response.setMsg("offer");
                }
                else if (answer == null) {
                    answer = session;
                    response.setMsg("answer");
                }
                else {
                    response.setMsg("none");
                }
                sendMessage(session, response);
                break;
            }
            case "start":
                sendMessage(offer, response);
                break;
            //发送 offer 的 SDP 对象
            case "send-offer":
                sendMessage(answer, response.setMsg(data.getMsg()));
                //发送 answer 的 SDP 对象
            case "send-answer":
                sendMessage(offer, response.setMsg(data.getMsg()));
                //交换 candidate 信息
            case "send-candidate": {
                sendOther(session, response.setMsg(data.getMsg()));
                break;
            }
        }



        //ctx.channel().writeAndFlush(new TextWebSocketFrame("【服务器单发了客户端的消息】:" + LocalDateTime.now() + ",消息为: " + content));
        //clients.writeAndFlush( new TextWebSocketFrame("【服务器群发了客户端的消息】:" + LocalDateTime.now() + ",消息为: " + content));
        //将客户端发送过来的消息刷到所有的channel中
//        for (Channel channel : clients) {
//            //channel.writeAndFlush(msg);
//            channel.writeAndFlush(
//                    new TextWebSocketFrame("【服务器接收到了客户端的消息】:" + LocalDateTime.now() + ",消息为: " + content));
//        }
    }

    public static void sendOther(Channel session, Message msg)
    {
        if (offer != null && session.id().asShortText().equals(offer.id().asShortText())) {
            sendMessage(answer, msg);
        }
        else if (answer != null && session.id().asShortText().equals(answer.id().asShortText())) {
            sendMessage(offer, msg);
        }
    }


    private static void sendMessage(Channel channel, Message msg)
    {
        channel.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(msg)));
    }

}
